#!/bin/bash
#
# SPDX-License-Identifier: BSD-2-Clause
#
#  Assuming
#
#    git clone https://sourceware.org/git/glibc.git
#    cd glibc
#
topdir="$(git rev-parse --show-toplevel)"
if [ -z "${topdir}" ]
then
  echo "Not a git dir?  Exit."
  exit 1
fi
cd "${topdir}"
glibc_conf="$(grep 'GNU C Library' configure.ac)"
if [ -z "${glibc_conf}" ]
then
  echo "No GLibc configure.ac?  Wrong git repo?  Exit."
  exit 1
fi
if [ ! -f version.h ]
then
  echo "No version.h file?  Exit."
  exit 1
fi
version=$(sed -n -e 's/#define VERSION "\(.*\)"/\1/p' version.h)
if [ -z "${version}" ]
then
  echo "Malformed version.h file.  Exit."
  exit 1
fi
if [ ! -d localedata/locales ]
then
  echo "No localedata/locales subdir.  Broken repo?  Exit."
  exit 1
fi
(
  cd localedata/locales
  cat <<-EOF
	/* This struct of collating elements data has been generated by fetching
	   locale data from a GLibc ${version} source dir on $(date +%F). */
	struct collating_element_t
	{
	  const char32_t *element;
	  const char *locale;
	};

	collating_element_t collating_element[] =
	{
	EOF
  grep -r collating-element * \
  | sed -e 's#^\([^:]*\):collating-element[ \t]*\([^ \t]*\)[ \t]*from[ \t]*"\(.*\)".*$#  { U"\3", "\1" }, /* \2 */#
	       s/<U\([[:xdigit:]]\{4\}\)>/\\U0000\1/g
	       s/<U\([[:xdigit:]]\{5\}\)>/\\U000\1/g
	       s/<U\([[:xdigit:]]\{6\}\)>/\\U00\1/g
	       s/iso14651_t1_common//g' \
  | sort
  echo "};"
) > lc_collelem.h
